import React, { useRef } from "react";
import style from "./style.module.scss";
import { modifyHeadPic } from "../../api/my";
import { useAppDispatch, useAppSelector } from "../../store/hooks";
import { getUserInfo } from "../../store/user/userSlice";

interface PropsType {
  // 取消
  onCancel: () => void;
  //确认
  onConfirm: () => void;
}

export const MyMack: React.FC<PropsType> = ({ onCancel, onConfirm }) => {
  const userId = useAppSelector((state) => state.user.userInfo.userId);
  const sessionId = useAppSelector((state) => state.user.userInfo.sessionId);
  const dispatch = useAppDispatch();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const handleUpload = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const tar = e.target as HTMLInputElement;
    if (tar.files) {
      const file = tar.files[0];
      await modifyHeadPic(userId, sessionId, file);
      dispatch(getUserInfo({ userId: userId.toString(), sessionId }));
      onConfirm();
    }
  };
  return (
    <div>
      {
        <div className={style.mask}>
          <div className={style.footer_box}>
            <div className={style.picture}>
              <div>拍照</div>
              <input type="file" style={{ display: "none" }} id="getFile" />
              <div id="getButtonFile" onClick={() => handleUpload()}>
                从手机相册选择
              </div>
            </div>
            <div className={style.cancel} onClick={() => onCancel()}>
              取消
            </div>
          </div>
          <input
            type="file"
            ref={fileInputRef}
            style={{ display: "none" }}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              handleChange(e)
            }
          />
        </div>
      }
    </div>
  );
};
